import {
	createApp
} from 'vue'
import {
	createStore
} from 'vuex'

// Create a new store instance.
const store = createStore({
	state() {
		return {
			count: 0,
			token: {
				access_token: "",
				expires_in: 0
			},
			result: {},
			img: ""

		}
	},
	mutations: {
		increment(state) {
			state.count++
		},
		saveToken(state, token) {
			state.token = token
		},
		saveResult(state, result) {
			state.result = result
		},
		saveImg(state, img) {
			state.img = img
		}
	},
	actions: {
		getToken({
			commit
		}, cb) {

			// 先从本地存储获取token，如果不存在，则获取，或者如果过期，则重新获取
			let token = uni.getStorageSync("token")

			let expires_at = token.expires_at
			// 验证token是否有效
			if (!token || Date.now() >= expires_at) {
				const url = "https://aip.baidubce.com/oauth/2.0/token"
				const API_KEY = "GColDfyeuwGGpeyUXT1Xo0eY"
				const API_SECRET = "CdmheIeNKhsvp6pmGSDEXXQw2VGp91iX"

				// return new Promise()
				uni.request({
					url: `${url}?grant_type=client_credentials&client_id=${API_KEY}&client_secret=${API_SECRET}`,
					method: "POST",
					timeout: 60000,
					success: (res) => {

						if (res.statusCode == 200) {
							const access_token = res.data.access_token
							const expires_in = res.data.expires_in

							const expires_at = Date.now() + expires_in * 1000
							// 存到store中
							commit("saveToken", {
								access_token,
								expires_at: expires_at
							})
							// 存到本地存储
							uni.setStorageSync('token', {
								access_token,
								expires_at: expires_at
							})

							typeof cb === 'function' && cb()
						}
					}
				})

			}
		}
	},


	getters: {
		token(state) {
			return state.token
		}
	}
})

export default store;